package v2

import (
	"github.com/gin-gonic/gin"
	"missC/middleware"
	"missC/model"
	"missC/oauth"
	"missC/utils/er"
	log "missC/utils/logs"
)

// Login 后台登陆
func Login(c *gin.Context) {
	var formData model.User
	_ = c.ShouldBindJSON(&formData)

	var code int

	if len(c.Query("code")) > 10 {
		log.Info("开启三方登录模式")
		gitee := oauth.NewGitee(c.Query("code"))
		//从数据库查询三方登陆登陆的账号
		formData, code = model.GetGitee(gitee.GetUser())
		if code == 200 {

			//登录成功传入用户名
			token, _ := middleware.GenToken(formData.Username)

			c.JSON(200, gin.H{
				"code":  code,
				"data":  formData.Username,
				"id":    formData.Id,
				"msg":   er.GetErr(code),
				"token": token,
			})
			return
		}
		//登录失败
		c.JSON(200, gin.H{
			"code":  code,
			"data":  formData.Username,
			"id":    formData.Id,
			"msg":   er.GetErr(code),
			"token": "",
		})
		return
	}

	formData, code = model.CheckLogin(formData.Username, formData.Password)
	//登录成功
	if code == 200 {
		//登录成功传入用户名
		token, _ := middleware.GenToken(formData.Username)

		c.JSON(200, gin.H{
			"code":  code,
			"data":  formData.Username,
			"id":    formData.Id,
			"msg":   er.GetErr(code),
			"token": token,
		})
		return
	}
	//登录失败
	c.JSON(200, gin.H{
		"code":  code,
		"data":  formData.Username,
		"id":    formData.Id,
		"msg":   er.GetErr(code),
		"token": "",
	})

}
func AddUser(c *gin.Context) {
	var formData model.User
	_ = c.ShouldBindJSON(&formData)

	var code int
	//判断用户是否存在
	code = model.CheckUser(formData.Username)
	if code == 202 {
		c.JSON(200, gin.H{
			"code":  code,
			"data":  formData.Username,
			"id":    formData.Id,
			"msg":   er.GetErr(code),
			"token": "",
		})
		return

	}
	//添加成功
	formData, code = model.AddUser(formData)
	c.JSON(200, gin.H{
		"code":  code,
		"data":  formData.Username,
		"id":    formData.Id,
		"msg":   er.GetErr(code),
		"token": "",
	})

}
